package com.espoir.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.espoir.shp.read02.Point;

import java.util.ArrayList;
import java.util.List;

public class JSONUtils {
    public static Point StringToPoint(String s){
        JSONObject jsonObject = JSON.parseObject(s);
        int x = jsonObject.getInteger("x");
        int y = jsonObject.getInteger("y");
        System.out.println("y = " + y);
        System.out.println("x = " + x);
        return new Point(x,y);
    }
    public static List<Point> StringArrToPoints(String s){
        List<Point> list = new ArrayList<>();
        JSONArray arr = JSON.parseArray(s);
        arr.forEach((item)->{
            int x = ((JSONObject) item).getInteger("x");
            int y = ((JSONObject) item).getInteger("y");
            Point point = new Point(x, y);
            list.add(point);
        });
        return list;
    }

    public static String PointToString(Point p){
        JSONObject jsonObj = new JSONObject();
        String jsonStr = "";
        try {
            jsonObj.put("x", p.getX());
            jsonObj.put("y", p.getY());

            jsonStr = jsonObj.toString();
        }catch (Exception e){
            e.printStackTrace();
        }
        return jsonStr;
    }

    public static String PointsToString(List<Point> list){
        JSONArray array = new JSONArray();

        String jsonStr = "";
        try {
            list.forEach((item)->{
                JSONObject jsonObj = new JSONObject();
                jsonObj.put("x", item.getX());
                jsonObj.put("y", item.getY());
                array.add(jsonObj);
            });

        }catch (Exception e){
            e.printStackTrace();
        }
        jsonStr = array.toString();
        return jsonStr;
    }
}
